package com.tdcy.workflow.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tdcy.framework.util.WebUtils;
import com.tdcy.workflow.entity.ActModel;

@Controller
@RequestMapping(value = "/workflow")
public class ModelController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	RepositoryService repositoryService;

	/**
	 * 模型列表
	 */
	@ResponseBody
	@RequestMapping(value = "/getModelList")
	public Object modelList() {
		List<Model> list = repositoryService.createModelQuery().list();
		List<ActModel> li = new ArrayList<ActModel>();
		for (Model model : list) {
			ActModel actmodel = new ActModel();
			actmodel.setId(model.getId());
			actmodel.setKey(model.getKey());
			actmodel.setCreateTime(model.getCreateTime());
			actmodel.setLastUpdateTime(model.getLastUpdateTime());
			actmodel.setMetaInfo(model.getMetaInfo());
			actmodel.setName(model.getName());
			actmodel.setVersion(model.getVersion().toString());
			li.add(actmodel);
		}
		return WebUtils.createJSONSuccess("success", list);
	}

	/**
	 * 创建模型
	 */
	@ResponseBody
	@RequestMapping(value = "/createModel", method = RequestMethod.POST)
	public Object createModel(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			ObjectNode editorNode = objectMapper.createObjectNode();
			editorNode.put("id", "canvas");
			editorNode.put("resourceId", "canvas");
			ObjectNode stencilSetNode = objectMapper.createObjectNode();
			stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
			editorNode.put("stencilset", stencilSetNode);
			Model modelData = repositoryService.newModel();

			ObjectNode modelObjectNode = objectMapper.createObjectNode();
			modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
			modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
			description = StringUtils.defaultString(description);
			modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
			modelData.setMetaInfo(modelObjectNode.toString());
			modelData.setName(name);
			modelData.setKey(StringUtils.defaultString(key));

			repositoryService.saveModel(modelData);
			repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
			map.put("modelId", modelData.getId());
		} catch (Exception e) {
			logger.error("创建模型失败：", e);
			return WebUtils.createJSONSuccess("创建模型成功");
		}
		return WebUtils.createJSONSuccess("创建模型成功");
	}

	/**
	 * 根据Model部署流程
	 */
	@ResponseBody
	@RequestMapping(value = "/deployModel")
	public Object deployModel(@RequestParam("modelId") String modelId) {
		try {
			Model modelData = repositoryService.getModel(modelId);
			ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
			byte[] bpmnBytes = null;

			BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
			bpmnBytes = new BpmnXMLConverter().convertToXML(model);

			String processName = modelData.getName() + ".bpmn20.xml";
			Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes)).deploy();
			logger.info("部署成功，部署ID=" + deployment.getId());
		} catch (Exception e) {
			logger.error("根据模型部署流程失败：modelId={}", modelId, e);
			return WebUtils.createJSONSuccess("部署失败:" + e.getMessage());
		}
		return WebUtils.createJSONSuccess("部署成功");
	}

	/**
	 * 导出model对象为指定类型
	 *
	 * @param modelId
	 *            模型ID
	 * @param type
	 *            导出文件类型(bpmn\json)
	 */
	@ResponseBody
	@RequestMapping(value = "/exportModel")
	public void exportModel(@RequestParam("modelId") String modelId, @RequestParam("type") String type, HttpServletResponse response) {
		try {
			Model modelData = repositoryService.getModel(modelId);
			BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
			byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());

			JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
			BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

			// 处理异常
			if (bpmnModel.getMainProcess() == null) {
				response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
				response.getOutputStream().println("no main process, can't export for type: " + type);
				response.flushBuffer();
				return;
			}

			String filename = "";
			byte[] exportBytes = null;
			String mainProcessId = bpmnModel.getMainProcess().getId();
			if (type.equals("bpmn")) {
				BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
				exportBytes = xmlConverter.convertToXML(bpmnModel);
				filename = mainProcessId + ".bpmn20.xml";
			} else if (type.equals("json")) {
				exportBytes = modelEditorSource;
				filename = mainProcessId + ".json";
			}

			ByteArrayInputStream in = new ByteArrayInputStream(exportBytes);
			IOUtils.copy(in, response.getOutputStream());

			response.setHeader("Content-Disposition", "attachment; filename=" + filename);
			response.flushBuffer();
		} catch (Exception e) {
			logger.error("导出model的xml文件失败：modelId={" + modelId + "}, type={}", type, e);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/deleteModel")
	public Object deleteModel(@RequestParam("modelId") String modelId) {
		repositoryService.deleteModel(modelId);
		return WebUtils.createJSONSuccess("删除成功");
	}

	@ResponseBody
	@RequestMapping(value = "/getPluginXml")
	public Object getPluginXml(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String path = ModelController.class.getClassLoader().getResource("plugins.xml").getPath();
		System.out.println("path = " + path);  
		File f = new File(path); 
		String pluginXml = FileUtils.readFileToString(f);
		try {
			response.setContentType("text/xml");
			response.getWriter().write(pluginXml);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
